package com.maschinenstuermer.profiler.model.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Trace {
	@XmlElementWrapper(name="methods")
	private List<ProfiledMethod> method = new ArrayList<ProfiledMethod>();
	
	@XmlElementWrapper(name="callStacks")
	private List<ThreadCallStack> callStack = new ArrayList<ThreadCallStack>();
	
	private transient Map<String, ProfiledMethod> nameToMethod = new HashMap<String, ProfiledMethod>();
	
	private transient Map<Long, ThreadCallStack> threadIdToCallStack = new HashMap<Long, ThreadCallStack>();
	
	/**
	 * Required by JAXB.
	 */
	public Trace() {	
	}

	public List<ThreadCallStack> getThreadCallStacks() {
		return Collections.unmodifiableList(callStack);
	}
	
	public ThreadCallStack getCurrentThreadCallStack() {
		Thread currentThread = Thread.currentThread();
		long id = currentThread.getId();
		ThreadCallStack threadCallStack = threadIdToCallStack.get(id);
		if (threadCallStack == null) {
			threadCallStack = new ThreadCallStack(currentThread.getName(), id);
			threadIdToCallStack.put(id, threadCallStack);
			callStack.add(threadCallStack);
		}
		return threadCallStack;
	}
	
	public void addProfiledMethod(String methodName) {
		if (!nameToMethod.containsKey(methodName)) {
			ProfiledMethod profiledMethod = new ProfiledMethod(methodName);
			method.add(profiledMethod);
			nameToMethod.put(methodName, profiledMethod);
		}
	}

	public ProfiledMethod getMethod(String methodName) {
		final ProfiledMethod result = nameToMethod.get(methodName);
		return result;
	}
	
	public List<ProfiledMethod> getMethods() {
		return method;
	}

	public void accept(ModelVisitor visitor) {
		visitor.visit(this);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((callStack == null) ? 0 : callStack.hashCode());
		result = prime * result + ((method == null) ? 0 : method.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Trace other = (Trace) obj;
		if (callStack == null) {
			if (other.callStack != null)
				return false;
		} else if (!callStack.equals(other.callStack))
			return false;
		if (method == null) {
			if (other.method != null)
				return false;
		} else if (!method.equals(other.method))
			return false;
		return true;
	}
}
